function resizeKanban(){
	var bodyHeight = $(window).height();

	if(bodyHeight < 300){
		$("#box_tasks ul").height(bodyHeight - 310);
		$("ul.sprints, .list_items").height(300);
	}else{
		$("#box_tasks ul").height(bodyHeight - 131);
		$("ul.sprints, .list_items").height(bodyHeight - 121);
	}
}

$(window).resize(function() {
	resizeKanban();	
});

$(document).ready(function() {	
	loadBacklog();
	loadSprints();
	resizeKanban();


	$("#menu_filter").click(function(){
		if($("#toolsbar .filter").css("display") == "none"){
			$("#toolsbar").slideUp('fast',function(){
				$(".tools_left > div",this).hide();
				$(".filter",this).show();

				$('#findBacklog').keyup(function(){
					var valField = new RegExp($(this).val(),"i");
					$("#backlog ul li").each(function(){
						if($(".title",this).text().search(valField) >= 0)
							$(this).css("display","block");
						else
							$(this).css("display","none");
					});
				});

				$(this).slideDown('slow');
			});
		}
	});

	$("#menu_add").click(function(){
		if($("#toolsbar .add").css("display") == "none"){
			$("#toolsbar").slideUp('fast',function(){
				$(".tools_left > div",this).hide();
				$(".add",this).show();

				$(this).slideDown('slow');
			});
		}
	});

	$("#toolsbar .cancel").click(function(){
		$("#toolsbar").slideUp('fast',function(){
			$(".tools_left > div",this).hide();
			$(".title",this).show();

			$(this).slideDown('slow');
		});
	});

	$("#newBacklog").click(function(){		
		newBacklog();
	});

	$("#newSprint").click(function(){		
		$.ajax({
			url: SITE+"app/Views/V_Sprint.php?f=newSprint",
			success: function(data){
				var obj = JSON.decode(data);
				resultNewSprint(obj);
			}
		});
	});	

});

function showModal(){
	resizeKanban();
}

function closeModal(){
	resizeKanban();
}


/******************************************************************************************************************
Sprint Functions
******************************************************************************************************************/
function loadSprints(){
	$.ajax({
		url: SITE+"app/Views/V_Sprint.php?f=getSprints",
		async: false,
		success: function(data){
			var obj = JSON.decode(data);
			$("#box_sprints").html('<div class="list_items right"><a title="Fechar" class="close_box"></a><div id="box_tasks"></div></div>'+obj[1]);

			$(".sprints li").droppable({
				hoverClass: "active_drop",
				drop: function( event, ui ) {
					var obj			= $(ui.draggable).children();
					var	idSprint	= $(this).attr("id").replace("sprint_","");

					if($(obj).attr("id").search("backlog_") == 0)
						createNewTask(obj,idSprint,0);
					else
						changeSprintTask(obj,idSprint);
				}
			});			

			$(".sprints li .description").click(function(){				
				setSprint($(this).parent());
			});
		}
	});

	return false;
}

function setSprint(obj){
	var	id = $(obj).attr("id").replace("sprint_","");

	if($("ul.sprints").data("sprint") != id){
		loadTasks(id);
	}else{
		openBoxTasks(id);
	}
	
	$("ul.sprints").data("sprint",id);
}

function resultNewSprint(obj){
	if(obj[0]){
		openBox("overlay", obj[1]);

		$("#formSprint").validate({
			submitHandler: function(form) {
				var query = $(form).serialize();
				
				$.ajax({
					url: SITE+"app/Views/V_Sprint.php?f=saveSprint&"+query,
					async: false,
					success: function(data){
						var obj = JSON.decode(data);

						if(obj[0])
							loadSprints();

						resultMensage(obj, obj[0]);
					}
				});

				return false;
			}
		});

		$(".date_pick").dateinput();
		$("#dateBegin").data("dateinput").setMin(obj[2].dateBegin);
		$("#dateBegin").data("dateinput").setMax(obj[2].dateEndEstimated);
		$("#dateEnd").data("dateinput").setMin(obj[2].dateBegin);
		$("#dateEnd").data("dateinput").setMax(obj[2].dateEndEstimated);

		$("#dateBegin").data("dateinput").change(function() {
			$("#dateEnd").data("dateinput").setMin(this.getValue(), true);
		});
	}else{
		resultMensage(obj, obj[0]);
	}
}

function editSprint(id){
	$.ajax({
		url: SITE+"app/Views/V_Sprint.php?f=editSprint&id="+id,
		success: function(data){
			var obj = JSON.decode(data);
			resultNewSprint(obj);
		}
	});
}

function deleteSprint(id){
	openBox("modalDelete");

	$("#modalDelete #confirm").click(function(){
		$.ajax({
			url: SITE+"app/Views/V_Sprint.php?f=deleteSprint&id="+id,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){
					$("#sprint_"+id).remove();
				}
				
				resultMensage(obj, true);
			}
		});
	});
}

function updateTasksSprints(){
	$.ajax({
		url: SITE+"app/Views/V_Sprint.php?f=getTaskSprints",
		success: function(data){
			var obj = JSON.decode(data);
			var x;
			for(x in obj[1]){				
				$("#sprint_"+obj[1][x].id+" .countTasks").html(obj[1][x].tasks);
			}
		}
	});
}

function checkSprint(id){
	$(".sprints li").removeClass("selected");
	$("#sprint_"+id).addClass("selected");
}

/******************************************************************************************************************
Backlog Functions
******************************************************************************************************************/
function loadBacklog(){
	$.ajax({
		url: SITE+"app/Views/V_Backlog.php?f=getBacklog",
		success: function(data){
			var obj = JSON.decode(data);
			$("#backlog").html(obj[1]);

			if(!obj[0])
				newBacklog();

			if(USER_GROUP <= 2){
				$(".list_items ul li").draggable({
					helper: "clone",
					zIndex: 9999,
					scroll:false,
					appendTo: "body",
					connectToSortable: "#box_tasks ul",
					start: function(event, ui) {					
						$(".details",$(ui.helper)).css("display","none");
						$(".buttons",$(ui.helper)).css("display","none");

						$(".details",$(this)).css("display","none");
						$(".buttons",$(this)).css("display","none");
					}
				});
			}

			$(".list_items .title_bar").click(function(){
				$(".buttons",$(this).parent()).slideToggle("fast");
			});

			$("#backlog button.expand").click(function(){
				var obj = $(this);
				$(".details",$(this).parent().parent()).slideToggle("fast",function(){
					if($(this).css("display") == "none"){
						obj.html("+");
					}else{
						obj.html("-");
					}
				});
			});

			$(".list_items .task").dblclick(function(){
				var id = $(this).attr("id").replace("backlog_","");
				if(USER_GROUP == 1){
					editBacklog(id);
				}else{
					viewBacklog(id);
				}
			});

			$("#backlog span.status").qtip({
				content: $(this).attr("title"),
				style: {name:'blue', tip:'leftMiddle', border:{radius:3}},
				position: {adjust: {y:-20, x:8}}
			});
		}
	});
}

function newBacklog(){
	$.ajax({
		url: SITE+"app/Views/V_Backlog.php?f=newBacklog",
		success: function(data){
			var obj = JSON.decode(data);
			resultNewBacklog(obj);
		}
	});
}

function resultNewBacklog(obj){	
	if(obj[0]){
		openBox("overlay", obj[1]);

		$("#formBacklog").validate({
			submitHandler: function(form) {
				var query = $(form).serialize();
				
				$.ajax({
					url: SITE+"app/Views/V_Backlog.php?f=saveBacklog&"+query,
					async: false,
					success: function(data){
						var obj = JSON.decode(data);

						if(obj[0])
							loadBacklog();

						resultMensage(obj, obj[0]);
						
					}
				});

				return false;
			}
		});
		
		var priorityClass = $("#formBacklog input[name=priorityClass]").val();
		if(priorityClass != "")
			$("ul.priority_colors li."+priorityClass).addClass("selected");

		
		$("ul.priority_colors li").click(function(){			
			$("#formBacklog input[name=priorityClass]").val($(this).attr("rel"));
			$("#formBacklog label[for=priorityClass]").hide();
			$("ul.priority_colors li").removeClass("selected");
			$(this).addClass("selected");
		});
		
	}else{
		resultMensage(obj, obj[0]);
	}
}

function editBacklog(id){
	$.ajax({
		url: SITE+"app/Views/V_Backlog.php?f=editBacklog&id="+id,
		success: function(data){
			var obj = JSON.decode(data);
			resultNewBacklog(obj);
		}
	});
}

function viewBacklog(id){
	$.ajax({
		url: SITE+"app/Views/V_Backlog.php?f=viewBacklog&id="+id,
		success: function(data){
			var obj = JSON.decode(data);
			if(obj[0])
				openBox("overlay", obj[1]);
			else
				resultMensage(obj, true);
		}
	});
}

function deleteBacklog(id){
	openBox("modalDelete");

	$("#modalDelete #confirm").click(function(){
		$.ajax({
			url: SITE+"app/Views/V_Backlog.php?f=deleteBacklog&id="+id,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){
					$("#backlog_"+id).remove();
				}
				
				resultMensage(obj, true);
			}
		});
	});
}

function updateTasksBacklog(){
	$.ajax({
		url: SITE+"app/Views/V_Backlog.php?f=getTaskBacklog",
		success: function(data){
			var obj = JSON.decode(data);
			var x;
			for(x in obj[1]){				
				$("#backlog_"+obj[1][x].id+" span.count_tasks").html("Tarefas: "+ obj[1][x].tasks +"/"+ obj[1][x].tasksFinish);
			}
		}
	});
}


/******************************************************************************************************************
Tasks Functions
******************************************************************************************************************/
function loadTasks(idSprint){
	$.ajax({
		url: SITE+"app/Views/V_Task.php?f=getTasks&idSprint="+idSprint,
		async: false,
		success: function(data){
			var obj = JSON.decode(data);
			$("#box_tasks").html(obj[1]);
			
			openBoxTasks(idSprint);

			$("#box_tasks > ul").height($(".list_items.right").height()-10);

			$("#box_tasks button.expand").click(function(){
				var obj = $(this);
				$(".details",$(this).parent().parent()).slideToggle("fast",function(){
					if($(this).css("display") == "none"){
						obj.html("+");
					}else{
						obj.html("-");
					}
				});
			});
			
			$(".list_items.right .close_box").unbind("click");
			$(".list_items.right .close_box").click(function(){				
				$(this).hide();
				$(".list_items.right").hide("slide",{direction:"right"});
				$(".sprints").width("auto");
			});
			
			$("#box_tasks .title_bar").click(function(){
				$("> .buttons",$(this).parent()).slideToggle("fast");
			});

			$("#box_tasks .task").dblclick(function(){
				var id = $(this).attr("id").replace("task_","");
				if(USER_GROUP <= 2){
					editTask(id);
				}else{
					viewTask(id);
				}

			});					

			if(USER_GROUP <= 2){
				$("#box_tasks .task").each(function(){
					$(this).data("sprint", idSprint);
				})

				$("#box_tasks > ul").sortable({
					containment: '#kanban',
					placeholder: 'placeholder',
					appendTo: '#kanban',
					start: function(event, ui) {
						$(".details",$(ui.item)).css("display","none");
						$(".buttons",$(ui.item)).css("display","none");
					},
					beforeStop: function(event, ui) {
						var idBacklog = $(ui.item).children().attr("id").replace("backlog_","");

						createNewTask($(ui.item).children(), $(".sprints").data("sprint"), ui.item.index());

						if(idBacklog > 0)
							ui.item.remove(); 
					},
					update: function(event, ui) {
						var idTask   = $(ui.item).children().attr("id").replace("task_","");
						var idSprint = $(".sprints").data("sprint");
						var ordersTasks = "";

						$("#box_tasks ul").children().each(function(){
							if(ordersTasks != "")
								ordersTasks += ",";
						
							if($(this).children().html() != null)
								ordersTasks += $(this).children().attr("id").replace("task_","");
						})
						
						$.ajax({
							url: SITE+"app/Views/V_Task.php?f=changeOrder&idSprint="+idSprint+"&order="+ordersTasks,
							success: function(data){
							}
						}); 
					}
				});
			}
			
			$("#box_tasks span.status").qtip({
				content: $(this).attr("title"),
				style: {name:'blue', border: {radius:3}, tip:true},
				position: {adjust:{y:0, x:-5}, corner:{target:'leftMiddle',tooltip:'rightMiddle'}}
			});
		}
	});

	return false;
}

function openBoxTasks(idSprint){		
	checkSprint(idSprint);
	
	var objListItems = $(".list_items.right");

	if(objListItems.css("display") == "none"){
		objListItems.show("slide",{direction:"right"},function(){
			$(".list_items.right .close_box").show();

			var boxSprints = $(".sprints").width();
			$(".sprints").width(boxSprints-268);
		});
	}else{
		$(".close_box",objListItems).show();
	}
}

function createNewTask(obj, idSprint, order){
	var idBacklog = $(obj).attr("id").replace("backlog_","");

	if(idBacklog > 0 && idSprint > 0){
		setSprint($("#sprint_"+idSprint));

		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=newTask&idSprint="+idSprint+"&idBacklogItem="+idBacklog+"&order="+order,
			success: function(data){
				var obj = JSON.decode(data);
				resultNewTask(obj);
			}
		});
	}
}

function resultNewTask(obj){	
	if(obj[0]){
		openBox("overlay", obj[1]);

		$("#formTask").validate({
			submitHandler: function(form) {
				var query = $(form).serialize();
				
				$.ajax({
					url: SITE+"app/Views/V_Task.php?f=saveTask&"+query,
					async: false,
					success: function(data){
						var obj = JSON.decode(data);

						if(obj[0]){
							loadTasks(form["idSprint"].value);
							updateTasksBacklog();
							updateTasksSprints();
						}
						
						resultMensage(obj, obj[0]);
					}
				});

				return false;
			}	
		});

		$(".date-pick").dateinput();
		$("#dateBegin").data("dateinput").setMin(obj[2].dateBegin);
		$("#dateBegin").data("dateinput").setMax(obj[2].dateEnd);
		$("#dateLimit").data("dateinput").setMin(obj[2].dateBegin);
		$("#dateLimit").data("dateinput").setMax(obj[2].dateEnd);

		$("#dateBegin").data("dateinput").change(function() {
			$("#dateLimit").data("dateinput").setMin(this.getValue(), true);
		});
	}else{
		resultMensage(obj, obj[0]);
	}
}

function editTask(id){
	$.ajax({
		url: SITE+"app/Views/V_Task.php?f=editTask&id="+id,
		success: function(data){
			var obj = JSON.decode(data);
			resultNewTask(obj);
		}
	});	
}

function viewTask(id){
	$.ajax({
		url: SITE+"app/Views/V_Task.php?f=viewTask&id="+id,
		success: function(data){
			var obj = JSON.decode(data);
			if(obj[0]){
				openBox("overlay", obj[1]);
			}else{
				resultMensage(obj, true);
			}
		}
	});	
}

function deleteTask(id){
	openBox("modalDelete");

	$("#modalDelete #confirm").click(function(){
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=deleteTask&id="+id,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){
					$("#task_"+id).remove();
					updateTasksSprints();
				}
				
				resultMensage(obj, true);
			}
		});
	});
}

function changeSprintTask(obj, idSprint){
	var idTask		 = $(obj).attr("id").replace("task_","");
	var idSprintTask = $(obj).data("sprint");

	if(idTask > 0 && idSprint > 0 && (idSprintTask != idSprint)){		
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=changeSprintTask&idSprint="+idSprint+"&idTask="+idTask,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){					
					updateTasksSprints();
					setSprint($("#sprint_"+idSprint));
				}
			}
		});
	}
}

function attachFile(idTask){
	if(idTask > 0){
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=addAttach&idTask="+idTask,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){					
					openBox("overlay", obj[1]);

					$("#uploadify").uploadify({
						'uploader'       : SITE + 'files/swf/uploadify.swf',
						'script'         : SITE + 'files/swf/uploadify.php',
						'cancelImg'      : SITE + 'files/images/icons/cross.png',
						'buttonImg'      : SITE + 'files/images/layout/selecionar_arquivos.gif',
						'width'          : 145,
						'height'         : 24,
						'queueID'        : 'fileQueue',
						'multi'          : true,
						'auto'           : true,
						'onAllComplete'	 : function(event, data) {
							$("#attachFiles button").attr("disabled", false);
						},
						'onInit'		 : function() {
							$("#attachFiles button").attr("disabled", true);
						},
						'onComplete'	 : function(event, queueID, fileObj, reposnse, data) {
							var temp = reposnse;
							if(temp != "0"){								
								$("#uploadSucess span").append(fileObj.name+"<br>");
								
								var countFiles = $('#attachFiles input[name*="files"]').length;
								
								$("<input>").attr({
									type: "hidden",
									name: "files"+countFiles,
									value: temp
								}).appendTo("#attachFiles");
									
								$('#attachFiles input[name="countFiles"]').val(countFiles+1);
							}
						}
					});					

					$("#attachFiles").validate({
						submitHandler: function(form) {
							var query = $(form).serialize();
							
							$.ajax({
								url: SITE+"app/Views/V_Task.php?f=saveAttach&"+query,
								success: function(data){
									var obj = JSON.decode(data);															
									resultMensage(obj, true);
								}
							});
						}
					});
				}
			}
		});	
	}
}

function deleteAttach(id){
	openBox("modalDelete");

	$("#modalDelete #confirm").click(function(){
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=deleteAttach&id="+id,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){
					$("#attach_"+id).remove();
				}
				
				resultMensage(obj, true);
			}
		});
	});
}